package com.denlaku.longan.service.impl;

import com.denlaku.longan.datac.ConnectionPool;
import com.denlaku.longan.datac.SqlExecutor;
import com.denlaku.longan.datac.SqlReturn;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.service.DataFetchService;
import com.denlaku.longan.service.DataOriginService;
import com.denlaku.longan.sql.SqlCommand;
import com.denlaku.longan.sql.SqlCommandBuilder;
import com.denlaku.longan.sql.SqlInfo;
import com.denlaku.longan.vo.DataSet;
import com.denlaku.longan.vo.DataOrigin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author tianx
 */
@Service
@Slf4j
public class DataFetchServiceImpl implements DataFetchService {
	@Autowired
	private SqlCommandBuilder sqlCommandBuilder;

	@Autowired
	private DataOriginService dataOriginService;

	@Override
	public SqlReturn query(SqlInfo info) {
		SqlCommand command = sqlCommandBuilder.build(info);
		DataSet dataSet = info.getDataSet();
		Long dataOriginId = dataSet.getDataOriginId();
		DataOrigin dataOrigin = dataOriginService.get(Query.of(dataOriginId));
		if (dataOrigin != null) {
			String password = dataOriginService.getPassword(Query.of(dataOriginId));
            dataOrigin.setPassword(password);
		}
		String sql = command.getSql();
		List<Object> params = command.getParams();
		Connection connection = null;
		try {
			connection = ConnectionPool.get(dataOrigin);
			return SqlExecutor.select(connection, sql, params);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		} finally {
			ConnectionPool.close(connection);
		}
		return null;
	}
}
